package server;

import utils.FileUtils;

public class GetRequest {
    
    private String askedFile;
    private static final String END_LINE = "\r\n";
    private static final String HTTP_200_OK = "HTTP/1.1 200 OK";
    private static final String HTTP_404_NOT_FOUND = "HTTP/1.1 404 Not Found";
    private static final String SERVER_NAME = "Server: ChezMoua/1.1 (Beurk Windows)";
    private static final String CONTENT_LENGTH = "Content-Length: ";
    private static final String CONTENT_TYPE_TEXT = "ContentType: text/html";
    private static final String ERROR_404 = "<!DOCTYPE HTML PUBLIC \"-//IETF//DTD HTML 2.0//EN\">\r\n" + 
    		"<html><head>\r\n" + 
    		"<title>404 Not Found</title>\r\n" + 
    		"</head><body>\r\n" + 
    		"<h1>Not Found</h1>\r\n" + 
    		"<p>The requested URL was not found on this server.</p>\r\n" + 
    		"</body></html>";

    public GetRequest(String requestData) {
        String[] requestArray = requestData.split("\n");
        String[] fileNameArray = requestArray[0].split("GET ");
        this.askedFile = "." + fileNameArray[1].split(" HTTP")[0];
    }
    
    public String getResponse() {
        String response = "";
        if (FileUtils.fileExist(this.askedFile)) {
            System.out.println("GetRequest : Reading the requested file...");
            response = this.getFileResponse();
        } else {
            System.out.println("GetRequest : Requested file does not exists, prepare 404 page...");
            response = this.get404Response();
        }
        return response;
    }
    
    /**
     * Build a String for a HTTP 404 Not found response
     * @return String HTTP 404 Not Found response
     */
    private String get404Response() {
        String response = HTTP_404_NOT_FOUND + END_LINE;
        response += SERVER_NAME + END_LINE;
        response += CONTENT_LENGTH + ERROR_404.length() + END_LINE;
        response += CONTENT_TYPE_TEXT + END_LINE;
        response += END_LINE;
        response += ERROR_404;
        return response;
    }
    
    /**
     * Build a String for a HTTP 200 OK response with the specified file
     * @return String HTTP 200 OK response with the file requested
     */
    private String getFileResponse() {
        String fileContent = FileUtils.getFileContent(this.askedFile);
        String response = HTTP_200_OK + END_LINE;
        response += SERVER_NAME + END_LINE;
        response += CONTENT_LENGTH + fileContent.length() + END_LINE;
        response += CONTENT_TYPE_TEXT + END_LINE;
        response += END_LINE;
        response += fileContent;
        return response;
    }
}
